package com.hzy.api;

import com.hzy.service.rag.RAGVerticle;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 负责处理 /api/rag/* 相关的 API 路由。
 */
public class RagApiVerticle extends AbstractVerticle {

    private static final Logger LOGGER = LoggerFactory.getLogger(RagApiVerticle.class);

    // 提供一个静态方法来获取此 Verticle 的 Router，供主 HttpServerVerticle 挂载
    public static Router createRouter(Vertx vertx) {
        Router router = Router.router(vertx);

        // RAG API 路由
        router.post("/generate").handler(context -> {
            JsonObject requestBody = context.body().asJsonObject();

            if (requestBody == null || !requestBody.containsKey("query")) {
                context.response().setStatusCode(400).end("Invalid request body. Required field: 'query'. Optional: 'model'.");
                return;
            }

            // 通过 Event Bus 请求 RAGVerticle
            vertx.eventBus().<JsonObject>request(RAGVerticle.RAG_REQUEST_ADDRESS, requestBody)
                    .onSuccess(ragReply -> {
                        context.response()
                                .end(ragReply.body().encodePrettily());
                    })
                    .onFailure(err -> {
                        LOGGER.error("Failed to get response from RAGVerticle: {}", err.getMessage());
                        context.fail(err);
                    });
        });
        return router;
    }
}